package org.hujunfeng.http;

import java.io.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author 胡俊丰
 * @Date 2024/10/4
 *
 * 封装HTTP响应对象
 **/
public class HttpResponse {

    /**
     * 响应码
     */
    private int code = 200;

    /**
     * 协议版本
     */
    private String version = "HTTP/1.1";

    /**
     * 协议状态
     */
    private String message = "OK";

    /**
     * 响应头的字段
     */
    private Map<String, String> headers;

    /**
     * 输出流
     */
    private OutputStream output;

    /**
     * 字符集
     */
    private String charset = "UTF-8";

    /**
     * 内容类别
     */
    private String contentType = "text/html;charset=UTF-8";

    public HttpResponse(OutputStream output){
        this.output = output;
        headers = new HashMap<String, String>();
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public void setHeader(String name, String value){
        headers.put(name, value);
    }

    /**
     * 发送响应头
     */
    public void sendResponseHead(){
        try {
            // 输出响应行
            output.write((version + " " + code + " " + message + "\r\n").getBytes("UTF-8"));

            // 输出内容类别
            output.write(("Content-Type: " + contentType + "\r\n").getBytes("UTF-8"));

            // 输出其他头部
            Iterator<String> iterator = headers.keySet().iterator();
            while (iterator.hasNext()){
                String key = iterator.next();
                String value = headers.get(key);

                // 头部的值不为空
                if (value != null){
                    output.write((key + ": " + value + "\r\n").getBytes("UTF-8"));
                }
            }

            // 输出空行
            output.write("\r\n".getBytes("UTF-8"));

            // 刷新数据
            output.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得响应体的输出流
     * @return
     */
    public OutputStream getBodyOutput(){
        return this.output;
    }

    /**
     * 获得响应体的打印器
     * @return
     */
    public PrintWriter getBodyWriter(){
        try {
            return new PrintWriter(new OutputStreamWriter(output, charset));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
}
